package com.xgzit.xgzmall.ware.service.impl;

import com.xgzit.common.constant.WareConstant;
import com.xgzit.xgzmall.ware.entity.PurchaseDetailEntity;
import com.xgzit.xgzmall.ware.service.PurchaseDetailService;
import com.xgzit.xgzmall.ware.service.WareSkuService;
import com.xgzit.xgzmall.ware.vo.MergeVo;
import com.xgzit.xgzmall.ware.vo.PurchaseDoneVo;
import com.xgzit.xgzmall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xgzit.common.utils.PageUtils;
import com.xgzit.common.utils.Query;

import com.xgzit.xgzmall.ware.dao.PurchaseDao;
import com.xgzit.xgzmall.ware.entity.PurchaseEntity;
import com.xgzit.xgzmall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


/**
 * @author xushuai
 */
@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService detailService;

    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
                        .eq("status", WareConstant.PurchaseStatusEnum.CREATE.getCode())
                        .or().eq("status", WareConstant.PurchaseStatusEnum.ASSIGNED.getCode())
        );

        return new PageUtils(page);
    }

    @SuppressWarnings("AlibabaTransactionMustHaveRollback")
    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if (Objects.isNull(purchaseId)) {
            // 1、新建采购单Id
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATE.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        // todo 确认采购单状态是 CREATE 或者 ASSIGNED 才可以合并
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = mergeVo.getItems().stream()
                .map(item -> {
                    PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                    detailEntity.setId(item);
                    detailEntity.setPurchaseId(finalPurchaseId);
                    detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
                    return detailEntity;
                }).collect(Collectors.toList());
        detailService.updateBatchById(collect);
        // 更新采购单时间
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    @Override
    public void received(List<Long> ids) {
        // 1、确认当前采购单是新建或者已分配状态
        List<PurchaseEntity> collect = ids.stream().map(this::getById)
                .filter(item -> item.getStatus() == WareConstant.PurchaseStatusEnum.CREATE.getCode() ||
                        item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode())
                .peek(item-> {
                    item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                    item.setUpdateTime(new Date());
                })
                .collect(Collectors.toList());

        // 2、改变 采购单 状态
        this.updateBatchById(collect);
        // 1、改变 采购项 状态
        collect.forEach(item->{
           List<PurchaseDetailEntity> entities = detailService.listDetailPurchaseId(item.getId());
            List<PurchaseDetailEntity> entityList = entities.stream().map(entity -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(entity.getId());
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return detailEntity;
            }).collect(Collectors.toList());
            detailService.updateBatchById(entityList);
        });
    }

    @Override
    public void createPurchase(PurchaseEntity purchase) {
        PurchaseEntity newPurchase = new PurchaseEntity();
        newPurchase.setPriority(purchase.getPriority());
        newPurchase.setCreateTime(new Date());
        newPurchase.setUpdateTime(new Date());
        newPurchase.setStatus(WareConstant.PurchaseStatusEnum.CREATE.getCode());
        this.save(newPurchase);
    }

    @SuppressWarnings("AlibabaTransactionMustHaveRollback")
    @Transactional
    @Override
    public void done(PurchaseDoneVo doneVo) {
        // 1、改变采购单的状态
        Long id = doneVo.getId();
        // 2、改变采购项的状态
        boolean flag = true;
        List<PurchaseItemDoneVo> items = doneVo.getItems();
            // 收集需要更新的数据
        List<PurchaseDetailEntity> updates = new ArrayList<>();
        for (PurchaseItemDoneVo item : items) {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HAS_ERROR.getCode()){
                flag = false;
                detailEntity.setStatus(item.getStatus());
            }else {
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                // 3、将采购成功的进行入库
                PurchaseDetailEntity entity = detailService.getById(item.getItemId());
                wareSkuService.addStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum());
            }
            detailEntity.setId(item.getItemId());
            updates.add(detailEntity);
        }
        detailService.updateBatchById(updates);
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag ? WareConstant.PurchaseDetailStatusEnum.FINISH.getCode(): WareConstant.PurchaseDetailStatusEnum.HAS_ERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

}
